import 'dart:convert';

import 'package:flutter_code_framework/model_data/user/data.dart';
import 'package:shared_preferences/shared_preferences.dart';

class User {
  UserData _user;

  /// 获取user
  UserData get data => _user;

  setData(UserData model) {
    _user = model;
    init(_user.toJson());
  }

  SharedPreferences _preferences;

  init(Map userJson) async {
    try {
      _user = UserData.fromJson(userJson);
    } catch (e) {
      return print('user init error, msg: $e');
    }

    await setString(userJson);

    return _user;
  }

  /// 保存到本地缓存
  setString(Map userJson) async {
    _preferences = await SharedPreferences.getInstance();
    _preferences.setString('userObject', json.encode(userJson));
  }

  //读取User信息
  Future<String> getString() async {
    _preferences = await SharedPreferences.getInstance();
    return _preferences.getString('userObject');
  }

  //删除用户信息
  delUserInfo() async {
    _preferences = await SharedPreferences.getInstance();
    _preferences.remove('userObject'); //删除指定键
    _user = null;
  }
}
